//
//  TTDiamondPopListView.m
//  TaoTuo
//
//  Created by 周晨晔 on 2019/9/24.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDiamondPopListView.h"
#import "TTShopCartDiamondViewCell.h"
#import "TTShopCartCommodityViewCell.h"
#import <UIView+TYAlertView.h>
#import "TTShopCartSubDetailModel.h"
#import "YBImageBrowser.h"

#import "TTQualityCheckPopListView.h"
#import "TTQualityCheckModel.h"

static NSString *luoshiCellID = @"luoshi_cell_id";
static NSString *shopCellID = @"shop_cell_id";

@interface TTDiamondPopListView ()<UITableViewDelegate, UITableViewDataSource, TTShopCartDiamondViewCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UILabel *leftLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UIButton *closeBtn;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) TTShopCartSubDetailModel *selectDetailModel;  //选中的model

@property (nonatomic, strong) NSMutableArray *qcListArray;  // 质检证书列表
@property (nonatomic, strong) TTQualityCheckPopListView *qcView;

@end

@implementation TTDiamondPopListView

+ (instancetype)popListViewWithDataArray:(NSArray *)dataArray
{
    NSInteger count = dataArray.count > 3 ? 3 : dataArray.count;
    CGFloat h = count * (65 * kScale + 40) + 50 + 50;
    h = h < 300 ? 300 : h;
    return [[self alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 40, h) dataArray:dataArray];
}

- (instancetype)initWithFrame:(CGRect)frame dataArray:(NSArray *)dataArray
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self configWithDataArray:dataArray];
        
    }
    return self;
}

- (void)configWithDataArray:(NSArray *)dataArray
{
    if (dataArray.count == 0) {
        return;
    }
    [self.dataArray addObjectsFromArray:dataArray];
    
    self.selectDetailModel = self.dataArray.firstObject;
    self.selectDetailModel.isSelect = YES;
    
    [self setupSubviews];
    
    [self.tableView reloadData];
    
    _qcView = [TTQualityCheckPopListView popListViewWithLastView:self];
    
    // 选中了某个裸石
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseDiamondNotify:) name:@"chooseDiamondNotify_key" object:nil];
    
    // 选择完质检证书点击完成之后的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseFinishedQualityCheckNotify:) name:@"chooseFinishedQualityCheckNotify_key" object:nil];
    
}

- (void)diamondPopListViewHiddenOrDismissNotify:(NSNotification *)notify
{
    int i = [notify.object intValue];
    if (i == 1) {
        [self dismissWithAnimationDuration:0];
    } else {
        self.hidden = NO;
    }
}

- (void)setupDataArray:(NSArray *)dataArray
{
    [self configWithDataArray:dataArray];
}

- (void)chooseDiamondNotify:(NSNotification *)notify
{
    for (TTShopCartSubDetailModel *model in self.dataArray) {
        model.isSelect = NO;
    }
    
    self.selectDetailModel = notify.object;
    self.selectDetailModel.isSelect = YES;
    [self.tableView reloadData];
    
}

- (void)chooseFinishedQualityCheckNotify:(NSNotification *)notify
{
    TTQualityCheckModel *qcModel = notify.object;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chooseAllFinishedNotify_key" object:@[self.selectDetailModel, qcModel]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartSubDetailModel *model = self.dataArray[indexPath.row];
    if (model.GoodsType == 1) {
        TTShopCartDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:luoshiCellID];
        [cell setDetailModel:model hasShadow:YES canSelect:YES cellWidth:self.width];
        cell.delegate = self;
        return cell;
    } else {
        TTShopCartCommodityViewCell *cell = [tableView dequeueReusableCellWithIdentifier:shopCellID];
        [cell setDetailModel:model hasShadow:YES canSelect:YES];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartSubDetailModel *model = self.dataArray[indexPath.row];
    if (model.isSelect) {
        return;
    }
    model.isSelect = YES;
//    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chooseDiamondNotify_key" object:model];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"needInlayLuoshiOrKongtuo_key" object:model];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartSubDetailModel *model = self.dataArray[indexPath.row];
    return model.h;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [self setupHeaderView];
}

- (void)clickLookCertificateWithModel:(TTShopCartSubDetailModel *)model
{
    // 查看证书
    [TTLoginSingle lookCertificateWithUrlString:model.CertPic];
}

// 下一步
- (void)nextPageAction:(UIButton *)sender
{
    sender.enabled = NO;    // 防止多次点击
    if (self.qcListArray.count > 0) {
        
        [self setQualityCheckData];
        
        return;
    }
    // 请求质检证书列表
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getQualityCheck_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        [self.qcListArray removeAllObjects];
        for (NSDictionary *dic in responseObject) {
            TTQualityCheckModel *model = [TTQualityCheckModel modelWithJSON:dic];
            [self.qcListArray addObject:model];
        }
        
        [self setQualityCheckData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.viewController.view];
    
}

- (void)setQualityCheckData
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DiaSizeMin <= %@ && DiaSizeMax > %@", self.selectDetailModel.DiaSize.numberValue, self.selectDetailModel.DiaSize.numberValue];
    NSArray *array = [self.qcListArray filteredArrayUsingPredicate:predicate];
    
    if (array.count == 0) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"没有符合的质检证书" duration:1 position:CSToastPositionCenter];
        return;
    }
    self.hidden = YES;
    self.qcView.dataArray = array;
    [self.qcView showInView:nil animationDuration:0.5];
    
    _rightBtn.enabled = YES;
}

// 关闭页面
- (void)closeBtnAction
{
    [self dismissWithAnimationDuration:0.3];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"closePopView_key" object:nil];
}

- (void)setupSubviews
{
    _closeBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"close_white"] target:self action:@selector(closeBtnAction)];
    [self addSubview:_closeBtn];
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.centerX.equalTo(self);
    }];
}

- (UIView *)setupHeaderView
{
    if (self.headerView) {
        return self.headerView;
    }
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 40)];
    headerView.backgroundColor = [UIColor whiteColor];
    self.headerView = headerView;
    
    _leftLabel = [UILabel labelWithTitle:@"1/2" color:UIColorHex(666666) fontSize:13];
    [headerView addSubview:_leftLabel];
    [_leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(headerView);
    }];
    
    _titleLabel = [UILabel labelWithTitle:@"该托可镶嵌的裸石" color:UIColorHex(000000) fontSize:15];
    [headerView addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(headerView);
    }];
    
    _rightBtn = [UIButton createButtonWithTitle:@"下一步" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:13] backgroundColor:nil target:self action:@selector(nextPageAction:)];
    [headerView addSubview:_rightBtn];
    [_rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headerView).mas_offset(-10);
        make.centerY.equalTo(headerView);
    }];
    
    return self.headerView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height - 50) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.layer.cornerRadius = 10;
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTShopCartDiamondViewCell class] forCellReuseIdentifier:luoshiCellID];
        [_tableView registerClass:[TTShopCartCommodityViewCell class] forCellReuseIdentifier:shopCellID];
        [self addSubview:_tableView];
        
    }
    return _tableView;
    
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)qcListArray
{
    if (!_qcListArray) {
        _qcListArray = [NSMutableArray array];
    }
    return _qcListArray;
}

- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
